package com.echoesnet.echoesshortvideo.Activities;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Constant.EsvConstant;
import com.echoesnet.echoesshortvideo.Beans.PublishVideoBean;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.GlideRoundTransform;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.RomUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.PublishVideoModel;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.orhanobut.logger.Logger;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Copyright (C) 2017 在线回声（天津）科技发展有限公司
 * 在线回声完全享有此软件的著作权，违者必究
 *
 * @author an
 * @version 1.0
 * @modifier
 * @createDate 2018/4/24 0024
 * @description 视频发布页面
 */
@RuntimePermissions
public class PublishVideoAct extends BaseActivity
{
    private final static String TAG = PublishVideoAct.class.getSimpleName();

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.img_thumbnail)
    ImageView imgThumbnail;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.tv_location)
    TextView tvLocation;

    private String mVideoPath; //视频路径
    private String mThumbnailPath;// 缩略图路径
    private String location; //定位名称
    private String posx;
    private String posy;
    private String startTime;//剪切开始时间
    private String endTime;//剪切时长
    private String showType;
    private PublishVideoModel publishVideoModel;
    private Activity mAct;
    private Dialog dialog;
    private boolean isCamera = false;
    private int degree = 0;
    private boolean isCutVideo = false;
    private CustomAlertDialog customAlertDialog;
//    private boolean isCutVideo = false;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_publish_video);
        ButterKnife.bind(this);
        mAct = this;

        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra("path");//视频地址
        showType = intent.getStringExtra("showType");//视频横向 竖向
        mThumbnailPath = intent.getStringExtra("thumbnailPath");//视频缩略图
        startTime = intent.getStringExtra("startTime");// 剪切开始时间
        endTime = intent.getStringExtra("endTime");//剪切结束时间
        isCamera = intent.getBooleanExtra("isCamera",false);//是否是拍摄视频
        degree = intent.getIntExtra("degree",0);//缩略图旋转角度
        Logger.t(TAG).d("videoPath >>" +mVideoPath + "|startTime >>" +startTime + "|endTime >>" +endTime + "|showType >>" +showType);
        etContent.setFilters(new InputFilter[]{new InputFilter(){
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
            {
                for (int i = start; i < end; i++) {
                    if (Character.isWhitespace(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }
        }});
        etContent.addTextChangedListener(new TextWatcher()
        {
            private CharSequence wordNum;//记录输入的字数
            private int selectionStart;
            private int selectionEnd;
            int num = 55;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                wordNum= charSequence;
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                //TextView显示剩余字数
                tvNum.setText(String.format("%s/55",s.length()));
                selectionStart=etContent.getSelectionStart();
                selectionEnd = etContent.getSelectionEnd();
                if (wordNum.length() > num) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    etContent.setText(s);
                    etContent.setSelection(s.length());//设置光标在最后
                }
            }
        });
        initDialog();
        publishVideoModel = ViewModelProviders.of(this).get(PublishVideoModel.class);
//        getThumbnail();
        compressVideo();
    }

    /**
     * 获取封面
     */
    private void getThumbnail()
    {
        if (TextUtils.isEmpty(mVideoPath))
            return;
        if (TextUtils.isEmpty(mThumbnailPath))
        {
            publishVideoModel.getThumbnail(true,0,mVideoPath,degree).observe(this, new Observer<PublishVideoBean>()
            {
                @Override
                public void onChanged(@Nullable PublishVideoBean publishVideoBean)
                {
                    String thumbnailPath = publishVideoBean.getThumbnails();
                    if (!TextUtils.isEmpty(thumbnailPath) && TextUtils.isEmpty(mThumbnailPath))
                    {
                        mThumbnailPath = thumbnailPath;
                        Logger.t(TAG).d("读取旋转角度>>>" + CommonUtils.getExifOrientation(mThumbnailPath));
                        GlideApp.with(AppController.getInstance())
                                .asBitmap()
                                .load(mThumbnailPath)
                                .apply(RequestOptions.bitmapTransform(new GlideRoundTransform(AppController.getInstance(),5)))
                                .into(imgThumbnail);
                    }
                }
            });
        }else {
            GlideApp.with(AppController.getInstance())
                    .asBitmap()
                    .load(mThumbnailPath)
                    .apply(RequestOptions.bitmapTransform(new GlideRoundTransform(AppController.getInstance(),5)))
                    .into(imgThumbnail);
        }
    }

    /**
     * 压缩视频
     */
    private void compressVideo( )
    {
        if ( !TextUtils.isEmpty(mVideoPath))
        {
            if (dialog != null)
                dialog.show();
            if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime))
            {
                publishVideoModel.cutVideo(startTime,endTime,mVideoPath).observe(this,publishVideoBean -> {
                    if (publishVideoBean == null)
                        return;
                    String url = publishVideoBean.getUrl();
                    if (!TextUtils.isEmpty(url))
                    {
                        mVideoPath = url;
                        getThumbnail();
                        if (dialog != null)
                            dialog.dismiss();
                        ToastUtils.showShort("视频压缩成功");
                        isCutVideo = true;
                    }
                });
            }else {
                publishVideoModel.compressVideo(mVideoPath).observe(this,publishVideoBean -> {
                    if (publishVideoBean == null)
                        return;
                    if (dialog != null && !TextUtils.isEmpty(publishVideoBean.getUrl()))
                    {
                        mVideoPath = publishVideoBean.getUrl();
                        getThumbnail();
                        dialog.dismiss();
                        ToastUtils.showShort("视频压缩成功");
                    }
                    isCutVideo = false;
                });
            }
        }
    }

    private void publishVideo()
    {
        if (!TextUtils.isEmpty(mVideoPath))
        {
            tvPublish.setClickable(false);
            if (dialog != null)
                dialog.dismiss();
            if (isCutVideo)
                CommonUtils.insertIntoMediaStore(mAct, true, mVideoPath, 0);
            if (!TextUtils.isEmpty(mVideoPath) && !TextUtils.isEmpty(mThumbnailPath))
            {
                if (isCamera)
                {
                    Observable.create(new ObservableOnSubscribe<String>()
                    {
                        @Override
                        public void subscribe(ObservableEmitter<String> emitter) throws Exception
                        {
                            String fileName = new File(mVideoPath).getName();
                            String destPath;
                            if (RomUtils.isVivo())
                            {
                                destPath = Environment.getExternalStorageDirectory().getPath() + File.separator +
                                        "相机";
                            }else {
                                destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator +
                                        "Camera";
                            }
                            Logger.t(TAG).d("移动到>>>>>>>>>>>>" + destPath);
                            CommonUtils.moveFile(mVideoPath,destPath);
                            mVideoPath = destPath + File.separator + fileName;
                            CommonUtils.insertIntoMediaStore(mAct, true, mVideoPath, 0);
                            emitter.onNext(mVideoPath);
                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<String>()
                            {
                                @Override
                                public void accept(String s) throws Exception
                                {
                                    sendPublishBroadCast();
                                }
                            });
                }else {
                    sendPublishBroadCast();
                }
            }
        }
    }

    private void sendPublishBroadCast()
    {
        String content = etContent.getText().toString().trim();
        Logger.t(TAG).d("发出广播>>>>>>>>>>>");
        Intent intent = new Intent(EsvConstant.ACTION_NOTIFY_PUBLISH_VIDEO);
        intent.putExtra("path",mVideoPath);
        intent.putExtra("thumbnailPath", mThumbnailPath);
        intent.putExtra("showType",showType);
        intent.putExtra("content",content);
        intent.putExtra("location",location);
        intent.putExtra("posx",posx);
        intent.putExtra("posy",posy);
        LocalBroadcastManager.getInstance(mAct).sendBroadcast(intent);
        finish();
    }


    private void initDialog()
    {

        View view = LayoutInflater.from(mAct).inflate(R.layout.dialog_compress_video,null);
        dialog = new Dialog(mAct,R.style.AlertDialogStyle);
        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
    }

    @OnClick({R.id.tv_publish,R.id.ll_location,R.id.img_back,R.id.rl_thumbnail})
    public void onViewClick(View view){
        switch (view.getId())
        {
            case R.id.tv_publish:
                if (CommonUtils.isFastDoubleClick())
                    return;
                publishVideo();
                break;
            case R.id.ll_location:
                PublishVideoActPermissionsDispatcher.onLocationGrantedWithPermissionCheck(this);
                break;
            case R.id.img_back:
                goBack();
                break;
            case R.id.rl_thumbnail:
                Intent intent1 = new Intent(mAct,PreviewVideoAct.class);
                intent1.putExtra("path",mVideoPath);
                intent1.putExtra("thumbnailPath", mThumbnailPath);
                startActivity(intent1);
                break;
        }
    }

    private void goBack()
    {
        if (customAlertDialog == null)
            customAlertDialog = new CustomAlertDialog(mAct)
                    .builder()
                    .setCancelable(false)
                    .setNegativeTextColor(ContextCompat.getColor(mAct, R.color.C0322))
                    .setPositiveTextColor(ContextCompat.getColor(mAct, R.color.C0321))
                    .setMsg("\n是否放弃发布拍摄的视频")
                    .setPositiveButton("继续发布", null)
                    .setNegativeButton("放弃", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if (isCamera && !TextUtils.isEmpty(mVideoPath))
                            {
                                new Thread(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        File file = new File(mVideoPath);
                                        if (file.exists())
                                            file.delete();
                                        File thumbnailFile = new File(mThumbnailPath);
                                        if (thumbnailFile.exists())
                                            thumbnailFile.delete();
                                    }
                                }).start();
                            }
                            finish();
                        }
                    });
        customAlertDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EsvConstant.OPEN_SELECT_LOCATION && resultCode == RESULT_OK)
        {
            boolean isShow = data.getBooleanExtra("isShow",false);
            if (isShow)
            {
                location = data.getStringExtra("locationName");
                posx = data.getStringExtra("latitude");
                posy = data.getStringExtra("longitude");
                Logger.t(TAG).d("位置>>>>locationName" + location +"| posx>>" + posx+"| posy>>" + posy);
                tvLocation.setText(location);
            }else
            {
                tvLocation.setText("你在哪?");
            }
        }
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION})
    void onLocationGranted()
    {
        Logger.t(TAG).d("允许获取权限");
        Intent intent = new Intent(mAct,SelectLocationAct.class);
        startActivityForResult(intent,EsvConstant.OPEN_SELECT_LOCATION);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION})
    void onLocationDenied()
    {
        Logger.t(TAG).d("拒绝获取权限");
        ToastUtils.showShort("没有获得相应的权限，无法为您进一步提供服务");
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION})
    void onLocationNeverAsk()
    {
        Logger.t(TAG).d("点击了不要再次询问获取权限");
        ToastUtils.showShort(getString(R.string.per_camera_never_ask));
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION})
    void onLocationPermReason(final PermissionRequest request)
    {
        Logger.t(TAG).d("说明");
        new CustomAlertDialog(mAct)
                .builder()
                .setTitle("请求权限说明")
                .setMsg("需要使用您的定位权限才能完成此功能！")
                .setPositiveButton("允许", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.cancel();
                    }
                }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PublishVideoActPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }

    @Override
    public void onBackPressed()
    {
        goBack();
    }

    @Override
    protected void onDestroy()
    {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
        super.onDestroy();
    }
}
